<script setup>

	import {ref, watch, onMounted} from 'vue'

	// 获取画布元素
	const signCanvas = ref(null)
	// 是否处于绘制状态
	let isDrawing = false
	// 获取画布上下文
	let ctx = null

	// 背景色
	const bgColor = ref('#fff')
	// 画笔颜色
	const penColor = ref('#000')

	const initSignCanvas = () => {
		const canvas = signCanvas.value
		ctx = canvas.getContext('2d')
		canvas.width = 600 // 设置canvas的实际宽度
		canvas.height = 300 // 设置canvas的实际高度
		ctx.fillStyle = bgColor.value
		ctx.fillRect(0, 0, canvas.width, canvas.height)
		ctx.strokeStyle = penColor.value
		ctx.lineWidth = 2
		ctx.lineJoin = 'round'
		ctx.moveTo(0, 0)
	}

	// 获取鼠标位置的函数
	const getMousePos = (canvas, event) => {
		const rect = canvas.getBoundingClientRect() // 获取canvas的边界矩形
		const scaleX = canvas.width / rect.width // 计算比例
		const scaleY = canvas.height / rect.height
		return {
			x: (event.clientX - rect.left) * scaleX,
			y: (event.clientY - rect.top) * scaleY
		}
	}

	// 鼠标事件处理
	const startDrawing = (event) => {
		isDrawing = true
		const pos = getMousePos(signCanvas.value, event)
		ctx.beginPath()
		ctx.moveTo(pos.x, pos.y)
	}

	const draw = (event) => {
		if (!isDrawing) return
		const pos = getMousePos(signCanvas.value, event)
		ctx.lineTo(pos.x, pos.y)
		ctx.stroke()
	}

	const stopDrawing = () => {
		isDrawing = false
		ctx.closePath()
	}

	// 保存签名
	const saveSignature = () => {
		const dataURL = signCanvas.value.toDataURL('image/png')
		const link = document.createElement('a')
		link.href = dataURL
		link.download = 'signature.png'
		link.click()
	}

	// 重置画布
	const resetCanvas = () => {
		ctx.clearRect(0, 0, signCanvas.value.width, signCanvas.value.height)
		ctx.fillStyle = '#fff'
		ctx.fillRect(0, 0, signCanvas.value.width, signCanvas.value.height)
	}

	// 事件绑定
	onMounted(() => {
		initSignCanvas()
	})

</script>

<template>

	<div class="hand-signature">
		<!--背景色选择器 画笔颜色选择器-->
		<div class="hand-signature-header flex mb20">
			<div>背景色：
				<el-color-picker v-model="bgColor" @change="initSignCanvas"></el-color-picker>
			</div>
			<div class="ml30">画笔色：
				<el-color-picker v-model="penColor" @change="initSignCanvas"></el-color-picker>
			</div>
		</div>
		<div class="hand-signature-content">
			<canvas id="signCanvas" ref="signCanvas"
					@mousedown="startDrawing"
					@mousemove="draw"
					@mouseup="stopDrawing"
					@mouseout="stopDrawing"
					style="width:100%;height:300px;"></canvas>
		</div>
		<div class="hand-signature-footer mt20">
			<el-button type="primary">保存</el-button>
			<el-button type="primary" @click="resetCanvas">重置</el-button>
		</div>
	</div>

</template>

<style scoped lang="scss">

	.hand-signature {
		width: 700px;
		height: 300px;
		margin: 100px auto;
	}

	.hand-signature-content {
		width: 100%;
		height: 100%;
		border: 1px solid #ccc;
	}
</style>
